<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Article;
use App\Models\ArticleRelateCircle;
use App\Models\Circle;
use App\Models\Star;
use App\Models\User;
use App\Models\UserJoinCircle;
use App\Models\UserNotInterest;
use App\Mongo\ArticleMon;
use Illuminate\Http\Request;
use YangJiSen\CacheUserProvider\CacheForget;


class ArticleController extends BaseController
{
    protected $model = Article::class;

    public function index(Request $request) {
        $input = $request->input();
        $search = ['start_at' => '', 'end_at' => '', 'type' => 0, 'status' => 1];
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');
        $is_special_choice = $request->input('is_special_choice', -1);
        $is_join_album = $request->input('is_join_album', -1);
        $circle_ids = $request->input('circle_ids');
        $circle_title = $request->input('circle_title');
        $arr_circle_id = explode(",", $circle_ids);
        $tag_ids = $request->input('article_tag');
        $arr_tag_id = explode(",", $tag_ids);
        $nickname = $request->input('nickname');
        $title = $request->input('title');
        $list = new Article();
        $action = $request->input('action');

        $arr_article_id = null;
        if ($action == 'not_interest') {
            $user_id = $request->input('user_id');
            $arr_article_id = UserNotInterest::where('user_id', $user_id)->pluck('article_id')->all();
        }

        if ($circle_title) {
            $arr_circle_id = Circle::where('title', 'like', '%' . $circle_title . '%')->pluck('id')->all();
            $list = $list->whereHas('circles', function ($qr) use($arr_circle_id) {
                $qr->whereIn('circle_id', $arr_circle_id);
            });
        }

        $list = $list->apply($search, $input)
            ->with(['circles' => function($q) {
                $q->select('title', 'circle_id');
            }])->withCertain('user', ['nickname'])
            ->with(['article_tag' => function($q) {
                $q->select('title', 'article_tags.id');
            }])->withCertain('user', ['nickname'])
            ->when(!is_null($arr_article_id), function ($q) use($arr_article_id) {
                $q->whereIn('id', $arr_article_id);
            })
            ->when(!empty($arr_tag_id[0]), function ($q) use($arr_tag_id) {
                $q->whereHas('article_tag', function ($qr) use($arr_tag_id) {
                    $qr->whereIn('article_tag_id', $arr_tag_id);
                });
            })
            ->when($nickname, function ($q) use($nickname) {
                $q->whereHas('user', function ($qr) use($nickname) {
                    $qr->where('nickname', 'like', '%' . $nickname . '%');
                });
            })
            ->when($title, function ($q) use($title) {
                $q->where('title', 'like', '%' . $title . '%');
            })
            ->when($is_special_choice != -1, function ($q) use($is_special_choice) {
                $q->where('is_special_choice', $is_special_choice);
            })
            ->when($is_join_album != -1, function ($q) use($is_join_album) {
                $q->where('is_join_album', $is_join_album);
            })
            ->orderBy($order_by_key, $order_by_value)->orderBy('id', 'desc')
            ->paginate(per_page());
        return $this->paginate($list);
    }

    public function info(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
        ]);
        $id = \request('id');
        $user_id = $this->getUserId();
        $info = Article::with(['comment' => function($qr) {
            $qr->select('id', 'user_id', 'message', 'entity_id')->limit(3);
        }, 'comment.user' => function($qr) {
            $qr->select('id', 'nickname');
        }])->withCount(['is_star' => function ($qr) use ($user_id) {
            $qr->where('user_id', $user_id)->where('type', Star::TYPE_COMMENT);
        }])->with(['circles' => function($qt) {
            $qt->select('title', 'circles.id');
        }])->with(['user' => function ($q) use($user_id){
            $q->select('id', 'nickname', 'weixin', 'avatar_url')->withCount(['is_focus' => function($qr) use($user_id) {
                $qr->where('focus.user_id', $user_id);
            }]);
        }, 'user.animal' => function ($q) {
            $q->select('user_id', 'title', 'birthday', 'category_title');
        }])->find($id);
        return $this->success($info);
    }

    public function choice_store(Request $request) {
       $this->validate($request, [
           'action' => 'required',
           'ids' => 'required'
       ]);
       $action = $request->input('action');
       $ids = $request->input('ids');
       $arr_ids = explode(",", $ids);
       if ($action == 'add') {
           Article::whereIn('id', $arr_ids)->update(['is_special_choice' => 1]);
       } else {
           Article::whereIn('id', $arr_ids)->update(['is_special_choice' => 0, 'sort' => 0]);
       }
       return $this->success([]);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $info = $this->model::find($id);
            if ($info->status == Article::STATUS_NORMAL) {
                $info->status = Article::STATUS_DELETE;
                ArticleMon::where('id', $info->id)->update([
                    'status' => Article::STATUS_DELETE
                ]);
                $info->save();
                $arr_old_article_id = $info->circles()->get(['circles.id'])->pluck('id');
                Circle::whereIn('id', $arr_old_article_id)->increment('feed_count', -1);
            } else {
                ArticleMon::where('id', $info->id)->delete();
                $info->delete();
                $user = User::find($info->user_id);
                $user->article_count -= 1;
                if ($user->article_count >= 0) {
                    $user->save();
                    CacheForget::CacheForget($user);
                }
                ArticleRelateCircle::where('article_id', $info->id)->delete();
            }
        }
        return $this->success([]);
    }

    public function restore(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $info = $this->model::find($id);
            $info->status = Article::STATUS_NORMAL;
            $info->save();

            $arr_old_article_id = $info->circles()->get(['circles.id'])->pluck('id');
            Circle::whereIn('id', $arr_old_article_id)->increment('feed_count', 1);
        }
        return $this->success([]);
    }

    public function setTag(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'tag_ids' => 'required',
        ]);
        $input = $request->input();
        $arr_id = explode(",", $input['ids']);
        $arr_tag_id = explode(",", $input['tag_ids']);
        foreach ($arr_id as $id) {
            $article = Article::find($id);
            if (!empty($arr_tag_id)) {
                ksort($arr_tag_id);
                $article->tag_ids = "," . implode(",", $arr_tag_id) . ",";
                $article->save();
            }
            $article->article_tag()->sync($arr_tag_id);
        }
        return $this->success([]);
    }

    public function assignUser(Request $request) {
        $new_user_id = \request('new_user_id');
        $ids = \request('ids');

        return \DB::transaction(function () use($ids, $new_user_id) {
            $arr_id = explode(",", $ids);
            foreach ($arr_id as $id) {
                $article = Article::find($id);
                $old_user_id = $article->user_id;
                if ($old_user_id == $new_user_id)
                    continue;

                $arr_circle_id = ArticleRelateCircle::where('article_id', $article->id)->pluck('circle_id')->all();

                $new_user = User::find($new_user_id);
                $circle_count = 0;
                foreach ($arr_circle_id as $circle_id) {
                    $userJoinCircle = UserJoinCircle::where('user_id', $new_user_id)->where('circle_id', $circle_id)->first();
                    if (!$userJoinCircle) {
                        UserJoinCircle::create([
                            'user_id' => $new_user_id,
                            'circle_id' => $circle_id
                        ]);
                        $circle_count += 1;
                        $circle = Circle::find($circle_id);
                        if ($circle) {
                            $circle->join_count += 1;
                            $circle->save();
                        }
                    }
                }

                $old_user = User::find($old_user_id);
                $old_user->article_count -= 1;
                if ($old_user->article_count >= 0)
                    $old_user->save();

                $article->user_id = $new_user_id;
                $article->save();

                $new_user->article_count += 1;
                $new_user->circle_count += $circle_count;
                $new_user->save();
            }
            return $this->success([]);
        });
    }

    public function circleStore(Request $request, $param = null)
    {
        $this->validate($request, [
            'id' => 'required',
            'circle_ids' => 'required',
        ]);
        $id = $request->input('id');
        $article = Article::find($id);
        if (!$article)
            return $this->failed('动态不存在');

        $activity_id = $article->activity_id;

        $input = $param ?: $request->input();
        $user_id = $article->user_id;
        $user = User::find($article->user_id);

        $circle_ids = $input['circle_ids'] ?? null;
        if ($circle_ids)
            $arr_circle_id = explode(",", $circle_ids);
        else
            $arr_circle_id = [];

        $city_code = $city = '';

        return \DB::transaction(function () use($id, $city_code, $city, $arr_circle_id, $activity_id, $user_id, $user, $param) {

            $article =  Article::find($id);
            $arr_old_article_id = $article->circles()->get(['circles.id'])->pluck('id')->all();
            $should_delete_arr = array_diff($arr_old_article_id, $arr_circle_id);
            $should_insert_arr = array_diff($arr_circle_id, $arr_old_article_id);
            Circle::whereIn('id', $should_delete_arr)->increment('feed_count', -1);
            Circle::whereIn('id', $should_insert_arr)->increment('feed_count', 1);

            $new_arr = [];
            foreach ($arr_circle_id as $val) {
                $new_arr[$val] = [
                    'article_user_id' => $article->user_id
                ];
            }
            $article->circles()->sync($new_arr);
            //同时设置关注圈子
            $circle_count = 0;
            foreach ($arr_circle_id as $circle_id) {
                $info = UserJoinCircle::where('user_id', $user_id)->where('circle_id', $circle_id)->first();
                if (!$info) {
                    UserJoinCircle::create([
                        'user_id' => $user_id,
                        'circle_id' => $circle_id,
                        'is_activity' => $activity_id ? 1 : 0
                    ]);
                    Circle::where('id', $circle_id)->increment('join_count', 1);
                    $circle_count += 1;
                    \Cache::forget(Circle::CACHE_CIRCLE_COVER_USER . "_" . $circle_id);
                }
            }

            if ($circle_count) {
                $user->circle_count += $circle_count;
                $user->save();
            }

            return $this->success(['id' => $id]);
        });
    }

}

